﻿using System;
using Line20.DateTimeRangeField.Settings;

namespace Line20.DateTimeRangeField.ViewModels {

    public class DateTimeRangeFieldViewModel {
        public string DisplayName { get; set; }

        public string StartDateTime { get; set; }
        public string EndDateTime { get; set; }

        public DateTimeRangeFieldDisplays Display { get; set; }

        private string _culture;
        public string Culture 
        {
            get { return !String.IsNullOrWhiteSpace(_culture) ? _culture : System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToString(); }
            set { _culture = value;  }
        }
        public string Hint { get; set; }
        public bool Required { get; set; }

        public string GetFormattedEndDate() {
            if (Display == DateTimeRangeFieldDisplays.DateAndTime) {
                DateTime? startDateTime = ConvertToDateTime(StartDateTime);
                DateTime? endDateTime = ConvertToDateTime(EndDateTime);

                if (IsSameDay(startDateTime, endDateTime))
                    return endDateTime.Value.ToShortTimeString();
            }

            return EndDateTime.ToString();
        }

        private bool IsSameDay(DateTime? startDateTime, DateTime? endDateTime) {
            if (!startDateTime.HasValue || startDateTime.Value == DateTime.MinValue || !endDateTime.HasValue || endDateTime.Value == DateTime.MinValue)
                return false;

            return endDateTime.Value.Subtract(startDateTime.Value).Days == 0;
        }

        private static DateTime? ConvertToDateTime(string dateTime) {
            DateTime value;

            if (!string.IsNullOrWhiteSpace(dateTime)) {
                if (DateTime.TryParse(dateTime, out value))
                    return value.ToUniversalTime();
            }

            return null;
        }
    }
}